package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.Exception.*;
import com.example.Utils.LoggerUtils;
import com.example.Utils.PasswordUtil;
import com.example.model.Admin;
import com.example.dao.AdminMapper;
import com.example.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Hello
 * @since 2024-07-03
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
    private static final Logger logger = LoggerUtils.getLogger(AdminServiceImpl.class);

    @Autowired
    AdminMapper adminMapper;
    @Override
    public Admin login(Admin admin) {
        if(!isRegister(admin)){
            throw new UnregisteredException("account is unregistered!");
        }
        Admin correctAdmin = getInfo(admin);
        if(correctAdmin == null){
            throw new ErrorPasswordOrAccountException("password or account is wrong!");
        }
        return correctAdmin;
    }

    @Override
    public Boolean isRegister(Admin admin) {
        QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
        adminQueryWrapper.eq("account",admin.getAccount());
        Admin one = adminMapper.selectOne(adminQueryWrapper);
        return one != null;
    }

    @Override
    public Admin Register(Admin admin) {
        if(!isRegister(admin)){
            throw new RegisteredException("account is registered!");
        }
        if(adminMapper.insert(admin) != 1) {
            throw new FailToRegisterException("fail to register!");
        }
        return admin;
    }

    @Override
    public Admin getInfo(Admin admin) {
        QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
        adminQueryWrapper.eq("account",admin.getAccount()).eq("password",PasswordUtil.encode(admin.getPassword()));
        Admin one = adminMapper.selectOne(adminQueryWrapper);
        if(one == null) {
            throw new UserNotExistException("user not exist!");
        }
        return one;
    }
}
